# -*- coding: utf-8 -*-
from utils.config import *
from utils.utils import *
import pandas as pd
import utils.MyTT as Mytt
# import logging
from utils.log import Loggers
from utils.pushService import PushService
import numpy as np

# 每小时的前5分钟 不调用脚本，防止数据不完整
should_skip()
logger = Loggers('junxianOne')
# logger.clear()

pushSer = PushService('正收益趋势策略')

# 动态调整ATR倍数（根据市场波动率）
def dynamic_multiplier(atr_ratio):
    # atr_ratio = myAtr / YearAtr
    if atr_ratio > 1.5:  # 高波动期
        return 1.5  
    elif atr_ratio < 0.7: # 低波动期
        return 3
    else:
        return 2.5
    
firstOne = 0
# 循环处理
for instId in config_movingAverage_instId:
    # 读取300条最新的数据
    try:
        df = loadCsvData(instId,'1d',300)
    except:
        continue
    
    df['ema10'] = Mytt.EMA(df['close'],10)

    # 计算k线实体和影线
    df['body'] = abs(df['close'] - df['open'])
    
    df['upper_shadow'] = np.where(df['close'] > df['open'], 
                             df['high'] - df['close'], 
                             df['high'] - df['open'])
    df['lower_shadow'] = np.where(df['close'] < df['open'], 
                             df['close'] - df['low'] , 
                              df['open'] - df['low'])

    # 默认相交
    df['cross_body'] = 1
    df.loc[ (df['close']>df['ema10']) & (df['open']>df['ema10']),'cross_body' ] = 0
    df.loc[ (df['close']<df['ema10']) & (df['open']<df['ema10']),'cross_body' ] = 0


    # 寻找开单信号
    df['signal'] = 0 
    # 做多信号  大级别多头趋势，收盘价>10均线 ，最高价不超过布林带上轨
    df.loc[(df['close'] > df['ema10']) & (df['cross_body'] == 0) & (df['upper_shadow']>df['body'] *2)  ,'signal'] = 1
    df.loc[(df['close'] < df['ema10']) & (df['cross_body'] == 0) & (df['lower_shadow']>df['body'] *2)  ,'signal'] = -1
    
    # 快速计算信号近期胜率
    # shenglv5,shenglv10 = getShenglv(df)
    # 取出所有满足条件的信号数据
    df_signal = df[df['signal']!=0]
    # print(df_signal.tail(30))
    # print(len(df_signal))
    # exit()
    # 拿到最后出现信号的数据
    after_signal = df_signal.iloc[-1]
    after_signal2 = df_signal.iloc[-2]

    xiaoshu = 1 if after_signal['close']>0 else 3
    # 计算止损点位
    zhisun= round(after_signal['recent_low'] + (after_signal['atr'] if after_signal['signal'] == -1 else after_signal['atr']*-1),xiaoshu)

    fangxiang = '做多' if after_signal['signal']>0 else '做空'
    signal_text = f"{instId}{fangxiang} 最近信号：{after_signal.name} 收盘价：{after_signal['close']} "

    fangxiang2 = '做多' if after_signal2['signal']>0 else '做空'
    diezhang = round(( after_signal['close'] - after_signal2['close']) / after_signal2['close'] * 100,2)
    signal_text2 = f"上次信号：{after_signal2.name}({fangxiang2}) 距今跌涨：{diezhang}%"

    # # 计算止损位置
    # zhisunR = round( abs((zhisun - after_signal['close'])) /after_signal['close'] *100,2)

    # signal_text+= f"止损：{zhisun}({zhisunR}%)"
    hour = getHoursPassed(after_signal.name)
    # 进行日志记录
    if hour < 25:
        if firstOne == 0:
            firstOne=1
            extent = [
                 signal_text2,
            f"固定止损：2%，止盈则收盘价跌破ema10均线\n\n",
            "温馨提示：\n\n",
            "策略属于趋势策略，小亏小赚，趋势来了需要拿稳\n\n",
            "策略回测正收益，胜率30%\n\n",
        ]
        else:
            extent = [
                 signal_text2,
            f"固定止损：2%，止盈则收盘价跌破ema10均线\n\n",
        ]
        # 25小时内的新信号 就可以 进行钉钉推送
        if pushSer.add_push_item(after_signal, instId,extent):
            logger.info(signal_text)

    # 完成消息的通知
pushSer.push_message()

